package com.gitee.cc.system.controller;

import com.gitee.cc.common.utils.ShiroUtils;
import com.gitee.cc.common.vo.AjaxResult;
import com.gitee.cc.system.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : cc
 * @date : Create in 15:10 2018/10/29
 */
@RestController
@Slf4j
public class LoginController {

    @PostMapping("/auth/login")
    public AjaxResult login(@RequestBody User user) {
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        Subject subjct = ShiroUtils.getSubjct();
        try {
            subjct.login(token);
        } catch (Exception e) {
            log.error("error={}", e);
            String msg = "";
            if (StringUtils.isEmpty(e.getMessage())){
                msg = "用户名或密码错误";
            }
            msg = e.getMessage();
            return AjaxResult.error().put("msg",msg);
        }
        return AjaxResult.success().put("user",ShiroUtils.getUser());
    }

}
